<template>
  <div class="home">
    <input type="text" v-model="title" @keydown.enter="search" />
    <hr />

    <button @click="remove">删除</button>
    <div class="con">
      <span v-for="(item, index) in history" :key="index">{{ item }}</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "",
      history: [],
    };
  },
  mounted() {
    if (localStorage.getItem("history")) {
      this.history = JSON.parse(localStorage.getItem("history"));
    }
    //如果本地存储中有就从本地存储中拿
  },

  methods: {
    search() {
      if (this.history.length < 3) {
        this.history.unshift(this.title);
        //历史记录小于3条的时候 就头部添加
      } else {
        this.history.pop();
        this.history.unshift(this.title);
        // 大于等于3的时候 尾部删除一个 再往头部添一个
      }

      localStorage.setItem("history", JSON.stringify(this.history));
      //把历史记录存在本地存储中
      this.$router.push({ path: "/result", query: { title: this.title } });
      //跳转到搜索结果页面，把搜索关键字传过去
    },
    remove() {
      this.history = [];
      localStorage.removeItem("history");
      //删除效果
    },
  },
};
</script>
<style lang="scss">
.con {
  span {
    background: #ccc;
    margin: 20px;
    width: 50px;
    display: inline-block;
  }
}
</style>
